package com.yazi.mxz.person.controller.shop;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;





import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.PageResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.Role;
import com.yazi.mxz.common.entity.beans.StoreMember;
import com.yazi.mxz.common.entity.beans.StoreMemberId;
import com.yazi.mxz.common.service.MemberService;
import com.yazi.mxz.common.service.RoleService;
import com.yazi.mxz.common.service.StoreMemberService;
import com.yazi.mxz.common.service.StoreService;
import com.yazi.mxz.person.common.Principal;
import com.yazi.mxz.person.common.Realm;
import com.yazi.mxz.person.jackson.filter.StoreMemberFilter;

@Controller("shop-storeMemberController")
@RequestMapping("/shop/storeMember")
public class StoreMemberController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(StoreMemberController.class);
	
	@Resource
	StoreMemberService storeMemberService;
	@Resource
	MemberService memberService;
	@Resource
	StoreService storeService;
	@Resource
	RoleService roleService;
	
	@RequestMapping("/list")
	public String list(Model model) {
		debug(log, "进入店铺管理员列表页面");
		
		Set<StoreMember> storeMembers = getStore(true).getStoreMembers();
		
		model.addAttribute("storeMembers", storeMembers);
		model.addAttribute("smId", getMemberId());
		
		return "shop/storeMember_list";
	}
	
	@RequestMapping("/add")
	public String add(Model model) {
		debug(log, "进入添加管理员页面");
		
		Role role = new Role();
		role.setStore(getStore());
		List<Role> roleList = roleService.list(role);
		model.addAttribute("roleList", roleList);
		return "shop/storeMember_add";
	}
	
	@RequestMapping("/addDo/json")
	@ResponseBody
	public StatusResult addDoJson(String userName, Long roleId) {
		debug(log, "添加管理员");
		StatusResult jsonResult = new StatusResult();
		Member member;
		StoreMemberId smId;
		StoreMember sm;
		try {
			member = new Member();
			member.setName(userName);
			List<Member> mList = memberService.list(member);
			if (mList.size() != 1) {
				jsonResult.setErrorMessage("用户不存在");
				return jsonResult;
			}
			
			member = mList.get(0);
			smId = new StoreMemberId();
			smId.setMemberId(member.getMemberId());
			sm = new StoreMember();
			sm.setId(smId);
			List<StoreMember> smList = storeMemberService.list(sm);
			if (smList.size() != 0) {
				jsonResult.setErrorMessage("该用户已是店铺管理员");
				return jsonResult;
			}
			
			smId.setStoreId(getStoreId());
			sm.setId(smId);
			storeMemberService.add(sm, roleId);
			jsonResult.setOkMessage("添加管理员成功");
		} catch (MyException e) {
			debug(log, "添加店铺管理员失败：" + e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "添加店铺管理员异常");
			jsonResult.setErrorMessage("保存失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/loginDo/json")
	@ResponseBody
	public ObjectResult<String> loginDoJson(String name, String pwd) {
		debug(log, "店铺营业员登录");
		ObjectResult<String> jsonResult = new ObjectResult<String>();
		try {
			
			
			Member member = memberService.oneByAccountName(name);
			if (null == member || MyUtil.checkPwd(member, pwd)) {
				jsonResult.setFailMessage("用户名或者密码错误");
				return jsonResult;
			} 
			
			// 只能登录当前店铺的管理员(用户)
			StoreMemberId storeMemberId = new StoreMemberId();
			storeMemberId.setMemberId(member.getMemberId());
			storeMemberId.setStoreId(getStoreId());
			StoreMember storeMember = storeMemberService.one(storeMemberId);
			if (null == storeMember) {
				jsonResult.setFailMessage("账户无效");
				return jsonResult;
			}
			
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			principal.setMember(member);
			SimplePrincipalCollection spc = new SimplePrincipalCollection(principal, Realm.class.getName());
			subject.runAs(spc);
			
			jsonResult.setResult(null == member.getRealName() ? member.getName() : member.getRealName());
			jsonResult.setOk();
			
		} catch (Exception e) {
			log.error("登录异常:", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}
	
	@RequestMapping("/delDo/json")
	@ResponseBody
	public StatusResult delDoJson(long memberId) {
		debug(log, "删除店铺管理员");
		StatusResult jsonResult = new StatusResult();
		StoreMemberId smId = new StoreMemberId();
		StoreMember storeMember;
		try {
			
			smId.setStoreId(getStoreId());
			smId.setMemberId(memberId);
			storeMember = storeMemberService.one(smId);
			if (null != storeMember) {
				storeMemberService.remove(storeMember);
			}
			jsonResult.setOk();
			
		} catch (MyException e) {
			debug(log, e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "删除店铺管理员异常");
			jsonResult.setErrorMessage("删除失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/list4Sync/json")
	@ResponseBody
	public PageResult<?> list4SyncJson(long updateTime, Searching si) {
		debug(log, "查询店铺管理员同步到本地 ");
		PageResult<StoreMember> jsonResult = new PageResult<StoreMember>();
		jsonResult.setFilter(StoreMemberFilter.getWithMember());
		StoreMember storeMember4s = new StoreMember();
		Page<StoreMember> page;
		try {
			
			storeMember4s.setStore(getStore());
			storeMember4s.setUpdateTime(updateTime);
			
			page = storeMemberService.listByGtUpdateTime(storeMember4s, si);
			jsonResult.setResult(page);
			jsonResult.setOk();
		} catch (Exception e) {
			error(log, e, "查询店铺管理员同步到本地异常");
			jsonResult.setErrorMessage("查找失败,请联系管理员");
		}
		return jsonResult;
	}
}
